package com.moody.hibernate.dao;

import java.util.*;

import org.hibernate.HibernateException;
import org.hibernate.LockMode;
import org.hibernate.Query;
import org.hibernate.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.moody.hibernate.domain.ReportList;
import com.moody.hibernate.domain.ReportListId;
import com.moody.util.CalendarUtil;

/**
 * A data access object (DAO) providing persistence and search support for
 * ReportList entities. Transaction control of the save(), update() and delete()
 * operations can directly support Spring container-managed transactions or they
 * can be augmented to handle user-managed Spring transactions. Each of these
 * methods provides additional information for how to configure it for the
 * desired type of transaction control.
 * 
 * @see com.moody.hibernate.domain.ReportList
 * @author MyEclipse Persistence Tools
 */

public class ReportListDAO extends HibernateDaoSupport {
	private static final Logger log = LoggerFactory
			.getLogger(ReportListDAO.class);
	// property constants
	public static final String REPORT_KIND = "reportKind";
	public static final String REPORT_CURRENCY = "reportCurrency";
	public static final String CURRENCY_UNIT = "currencyUnit";
	public static final String REPORT_STATUS = "reportStatus";
	public static final String AUDIT_STATUS = "auditStatus";
	public static final String INPUT_USER_ID = "inputUserId";
	public static final String INPUT_ORG_ID = "inputOrgId";
	public static final String INPUT_DATE = "inputDate";
	public static final String UPDATE_USER_ID = "updateUserId";
	public static final String UPDATE_ORG_ID = "updateOrgId";
	public static final String UPDATE_DATE = "updateDate";

	protected void initDao() {
		// do nothing
	}

	public void save(ReportList transientInstance) {
		log.debug("saving ReportList instance");
		try {
			getHibernateTemplate().saveOrUpdate(transientInstance);
			log.debug("save successful");
		} catch (RuntimeException re) {
			log.error("save failed", re);
			throw re;
		}
	}

	public void delete(ReportList persistentInstance) {
		log.debug("deleting ReportList instance");
		try {
			getHibernateTemplate().delete(persistentInstance);
			log.debug("delete successful");
		} catch (RuntimeException re) {
			log.error("delete failed", re);
			throw re;
		}
	}

	public ReportList findById(com.moody.hibernate.domain.ReportListId id) {
		log.debug("getting ReportList instance with id: " + id);
		try {
			ReportList instance = (ReportList) getHibernateTemplate().get(
					"com.moody.hibernate.domain.ReportList", id);
			return instance;
		} catch (RuntimeException re) {
			log.error("get failed", re);
			throw re;
		}
	}

	public List findByExample(ReportList instance) {
		log.debug("finding ReportList instance by example");
		try {
			List results = getHibernateTemplate().findByExample(instance);
			log.debug("find by example successful, result size: "
					+ results.size());
			return results;
		} catch (RuntimeException re) {
			log.error("find by example failed", re);
			throw re;
		}
	}

	public List findByProperty(String propertyName, Object value) {
		log.debug("finding ReportList instance with property: " + propertyName
				+ ", value: " + value);
		try {
			String queryString = "from ReportList as model where model."
					+ propertyName + "= ?";
			return getHibernateTemplate().find(queryString, value);
		} catch (RuntimeException re) {
			log.error("find by property name failed", re);
			throw re;
		}
	}

	public List findByReportKind(Object reportKind) {
		return findByProperty(REPORT_KIND, reportKind);
	}

	public List findByReportCurrency(Object reportCurrency) {
		return findByProperty(REPORT_CURRENCY, reportCurrency);
	}

	public List findByCurrencyUnit(Object currencyUnit) {
		return findByProperty(CURRENCY_UNIT, currencyUnit);
	}

	public List findByReportStatus(Object reportStatus) {
		return findByProperty(REPORT_STATUS, reportStatus);
	}

	public List findByAuditStatus(Object auditStatus) {
		return findByProperty(AUDIT_STATUS, auditStatus);
	}

	public List findByInputUserId(Object inputUserId) {
		return findByProperty(INPUT_USER_ID, inputUserId);
	}

	public List findByInputOrgId(Object inputOrgId) {
		return findByProperty(INPUT_ORG_ID, inputOrgId);
	}

	public List findByInputDate(Object inputDate) {
		return findByProperty(INPUT_DATE, inputDate);
	}

	public List findByUpdateUserId(Object updateUserId) {
		return findByProperty(UPDATE_USER_ID, updateUserId);
	}

	public List findByUpdateOrgId(Object updateOrgId) {
		return findByProperty(UPDATE_ORG_ID, updateOrgId);
	}

	public List findByUpdateDate(Object updateDate) {
		return findByProperty(UPDATE_DATE, updateDate);
	}

	public List findAll() {
		log.debug("finding all ReportList instances");
		try {
			String queryString = "from ReportList";
			return getHibernateTemplate().find(queryString);
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}

	public ReportList merge(ReportList detachedInstance) {
		log.debug("merging ReportList instance");
		try {
			ReportList result = (ReportList) getHibernateTemplate().merge(
					detachedInstance);
			log.debug("merge successful");
			return result;
		} catch (RuntimeException re) {
			log.error("merge failed", re);
			throw re;
		}
	}

	public void attachDirty(ReportList instance) {
		log.debug("attaching dirty ReportList instance");
		try {
			getHibernateTemplate().saveOrUpdate(instance);
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}

	public void attachClean(ReportList instance) {
		log.debug("attaching clean ReportList instance");
		try {
			getHibernateTemplate().lock(instance, LockMode.NONE);
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}

	public static ReportListDAO getFromApplicationContext(ApplicationContext ctx) {
		return (ReportListDAO) ctx.getBean("ReportListDAO");
	}
	
	/*
	 * 以下方法非自动生成
	 * 由自己添加
	 */
	
	 public void update(ReportList transientInstance) {
	        log.debug("updating ReportList instance");
	        try {
	            getHibernateTemplate().update(transientInstance);
	            log.debug("update successful");
	        } catch (RuntimeException re) {
	            log.error("update failed", re);
	            throw re;
	        }
	    }
	
	//查找最近一期,一年，两年，以及三年的报表
	public Map findRecentReport(String custId) {
		
		Map<String,ReportList> map = new LinkedHashMap<String,ReportList>();
		
		//查找最近一期
		String queryString = "from ReportList where custId = ? order by accountMonth";
		List<ReportList> list = getHibernateTemplate().find(queryString, custId);
		
		if(list!=null && list.size()>0){
			map.put(list.get(list.size()-1).getId().getAccountMonth(), list.get(list.size()-1));
		}
		else{
			map.put("0", null);
		}
		
		//查找最近年报
		String query = "from ReportList where custId = ? and  reportKind = ? order by accountMonth desc ";
		List<ReportList> reportList = getHibernateTemplate().find(query, custId, "01");
		
		if(reportList.size()>=3){
			Integer firstYear = Integer.parseInt(reportList.get(0).getId().getAccountMonth().substring(0, 4));
			Integer secondYear = Integer.parseInt(reportList.get(1).getId().getAccountMonth().substring(0, 4));
			Integer thirdYear = Integer.parseInt(reportList.get(2).getId().getAccountMonth().substring(0, 4));
			//查找最近一年
			map.put(firstYear+"",findReportByTime(custId,firstYear+"",firstYear+1+"" ));
			//查找最近两年
			map.put(secondYear+"", findReportByTime(custId,secondYear+"",secondYear+1+"" ));
			//查找第三年
			map.put(thirdYear+"", findReportByTime(custId, thirdYear+"",thirdYear+1+"" ));
		}else if(reportList.size()==2){
			Integer firstYear = Integer.parseInt(reportList.get(0).getId().getAccountMonth().substring(0, 4));
			Integer secondYear = Integer.parseInt(reportList.get(1).getId().getAccountMonth().substring(0, 4));
			Integer thirdYear = secondYear-1;
			//查找最近一年
			map.put(firstYear+"",findReportByTime(custId,firstYear+"",firstYear+1+"" ));
			//查找最近两年
			map.put(secondYear+"", findReportByTime(custId,secondYear+"",secondYear+1+"" ));
			//查找第三年
			map.put(thirdYear+"", findReportByTime(custId, thirdYear+"",thirdYear+1+"" ));
		}else if(reportList.size() == 1){
			Integer firstYear = Integer.parseInt(reportList.get(0).getId().getAccountMonth().substring(0, 4));
			Integer secondYear = firstYear-1;
			Integer thirdYear = secondYear-1;
			//查找最近一年
			map.put(firstYear+"",findReportByTime(custId,firstYear+"",firstYear+1+"" ));
			//查找最近两年
			map.put(secondYear+"", findReportByTime(custId,secondYear+"",secondYear+1+"" ));
			//查找第三年
			map.put(thirdYear+"", findReportByTime(custId, thirdYear+"",thirdYear+1+"" ));
		}else if(reportList.size() == 0){
			Integer firstYear = Integer.parseInt(CalendarUtil.getCurrentYearStr()) -1 ;
			Integer secondYear = firstYear-1;
			Integer thirdYear = secondYear-1;
			//查找最近一年
			map.put(firstYear+"",findReportByTime(custId,firstYear+"",firstYear+1+"" ));
			//查找最近两年
			map.put(secondYear+"", findReportByTime(custId,secondYear+"",secondYear+1+"" ));
			//查找第三年
			map.put(thirdYear+"", findReportByTime(custId, thirdYear+"",thirdYear+1+"" ));
		}

		
		return map;
	}

	
	public List findByCustId(String custId){
		String queryString = "from ReportList where custId = ?";
		return getHibernateTemplate().find(queryString, custId);
	}

	
	//查找某一年份的报表
	@SuppressWarnings("unchecked")
	public ReportList findReportByTime(String custId, String beginDate, String endDate){
		String query = "from ReportList where custId = ? and reportKind = ? and AccountMonth >=  ? and AccountMonth <= ?";
		List<ReportList> list = getHibernateTemplate().find(query,custId,"01",beginDate,endDate);
		
		if(list!=null && list.size()>0)
			return list.get(list.size()-1);
		else
			return null;
	}
	//查找某一年份的报表
	@SuppressWarnings("unchecked")
	public ReportList findReportByTime(String custId, String accountMonth){
		String query = "from ReportList where custId = ? and reportKind = ? and AccountMonth =  ?";
		List<ReportList> list = getHibernateTemplate().find(query,custId,"01",accountMonth);
		
		if(list!=null && list.size()>0)
			return list.get(list.size()-1);
		else
			return null;
	}

	//更新报表状态
	@SuppressWarnings("unchecked")
	public void updateReportStatus(final ReportList report, final String status) {
		
		getHibernateTemplate().execute(new HibernateCallback() {
			public Object doInHibernate(Session session) throws HibernateException {
			Query query = session.createQuery("update ReportList as model set model.reportStatus = ? " +
					"where model.id.custId = ? and model.id.accountMonth = ? and model.id.reportScope = ?");
			query.setParameter(0, status);
			query.setParameter(1, report.getId().getCustId());
			query.setParameter(2, report.getId().getAccountMonth());
			query.setParameter(3, report.getId().getReportScope());
			
			return query.executeUpdate();
			}
		});
	}
	
	//根据当期财务报表，查找上一期年度报表
	@SuppressWarnings("unchecked")
	public ReportList findPreviousYearReport(ReportList report) {
		String date = report.getId().getAccountMonth();
		String year = date.substring(0, 4);
		String previousYear = Integer.parseInt(year)-1+"";
		
		String query = "from ReportList where custId = ?  and AccountMonth >  ? and AccountMonth < ? ";
		List<ReportList> list = getHibernateTemplate().find(query,report.getId().getCustId(),previousYear,year);
		
		if(list!=null && list.size()>0)
			return list.get(list.size()-1);
		else
			return null;
	}
}